package camera;
import java.awt.*;
import java.awt.image.*;
import java.applet.*;
import java.net.*;
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JApplet;
import javax.imageio.*;
import javax.swing.event.*;

public class sobel {

	private Object Pixel;

	public java.awt.image.BufferedImage FiltroSobel(int[][] pixelAtual) {
		// this.Pixel p = new this.Pixel();
		int Gx, Gy;

		// pego o bufferedImage a fim de conseguir a largura a altura da imagem

		// obtendo largura e altura da imagem
		int w = pixelAtual.length, h = pixelAtual[0].length;

		for (int j = 0; j < h - 1; j++) {
			for (int i = 0; i < w - 1; i++) {
				if (i != 0) {
					if (j != 0) {
						Gx = (((-1) * pixelAtual[i - 1][j - 1] + (-2)
								* pixelAtual[i - 1][j] + (-1)	
								* pixelAtual[i - 1][j + 1]) / 4 - (pixelAtual[i + 1][j - 1]
								+ 2 * pixelAtual[i + 1][j] + 1 * pixelAtual[i + 1][j + 1]) / 4) / 2;

						Gy = (((-1) * pixelAtual[i - 1][j - 1] + (-2)
								* pixelAtual[i][j - 1] + (-1)
								* pixelAtual[i + 1][j - 1]) / 4 - (pixelAtual[i - 1][j + 1]
								+ 2 * pixelAtual[i][j + 1] + pixelAtual[i + 1][j + 1]) / 4) / 2;

						pixelAtual[i][j] = pixelAtual[i][j] = (int) Math
								.sqrt(Gx * Gx + Gy * Gy);// Gx*Gx + Gy*Gy;

					}
				}
			}
		}

		return this.setPixelEscalaDeCinza(pixelAtual);
	}

	public BufferedImage setPixelEscalaDeCinza(int[][] mtzImg) {
		int largura = mtzImg.length;
		int altura = mtzImg[0].length;

		BufferedImage image = new BufferedImage(largura, altura,
				BufferedImage.TYPE_BYTE_GRAY);

		WritableRaster raster = image.getRaster();
		for (int h = 0; h < largura; h++) {
			for (int w = 0; w < altura; w++) {
				raster.setSample(h, w, 0, mtzImg[h][w]);
			}
		}

		return image;
	}

}
